package com.thiny.android.game.thunderbolt.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MotionEvent;
import android.widget.ProgressBar;

import com.thiny.android.game.thunderbolt.R;
import com.thiny.android.game.thunderbolt.role.Player;
import com.thiny.android.game.thunderbolt.service.ThunderBoltService;
import com.thiny.android.game.thunderbolt.util.Constants;
import com.thiny.android.game.thunderbolt.view.GameView;

public class GameActivity extends Activity {

	private GameView mGameView;
	// 游戏触摸点坐标
	private float touchX, touchY;
	// 玩家飞机对象
	private Player mPlayer;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		ProgressBar progressBar = new ProgressBar(this);
		setContentView(progressBar);
		mGameView = new GameView(this, Constants.LEVEL_1);
		// LogUtil.i("完成耗时："+(System.currentTimeMillis()-a));
		setContentView(mGameView);
		mPlayer = mGameView.getPlayer();
		startService(new Intent(this, ThunderBoltService.class));
	}

	// 触屏控制我方飞机的移动
	@Override
	public boolean onTouchEvent(MotionEvent event) {

		int eventAction = event.getAction();
		switch (eventAction) {
		case MotionEvent.ACTION_DOWN:
			touchX = event.getX();
			touchY = event.getY();
			mGameView.setFire(true);
			break;
		case MotionEvent.ACTION_MOVE:

			float offsetX = event.getX() - touchX;
			float offsetY = event.getY() - touchY;

			mPlayer.move(offsetX, offsetY);

			touchX = event.getX();
			touchY = event.getY();
			break;
		case MotionEvent.ACTION_UP:
			mGameView.setFire(false);
			break;
		}

		return super.onTouchEvent(event);
	}

	// 退出游戏画面,结束服务
	@Override
	protected void onStop() {
		stopService(new Intent(this, ThunderBoltService.class));
		super.onStop();
	}

	// 游戏中的MENU只用于暂停/继续游戏
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.game_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	// menu开启时候，暂停游戏
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		mGameView.gameOnPause(true);
		return super.onMenuOpened(featureId, menu);
	}

	// menu关闭时候，暂停游戏
	@Override
	public void onOptionsMenuClosed(Menu menu) {
		mGameView.gameOnPause(false);
		super.onOptionsMenuClosed(menu);
	}

	@Override
	protected void onDestroy() {
		mGameView = null;
		super.onDestroy();
	}

}
